package com.huatai.datacenter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * ExecutorService配置类
 *
 * @author lizhong
 */
@Configuration
public class ExecutorServiceConfig {

	/**
	 * 项目开始时创建ExecutorService类的Bean
	 *
	 * @return ExecutorService
	 */
//	@Bean
	public ExecutorService executorService() {
		// 初始化executorService
		Runtime runtime = Runtime.getRuntime();
		int corePoolSize = Math.max(10, runtime.availableProcessors() * 2);
		int maximumPoolSize = Math.max(20, runtime.availableProcessors() * 2);
		ThreadFactory threadFactory = new ThreadFactory() {
			private final AtomicLong threadIndex = new AtomicLong(0);

			@Override
			public Thread newThread(Runnable r) {
				return new Thread(r, "QueryGroup_" + this.threadIndex.incrementAndGet());
			}
		};
		RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardOldestPolicy();
		// 初始化executorService

		ExecutorService executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS,
			new LinkedBlockingQueue<>(5000), threadFactory, handler);

		return executorService;
	}
}
